package face.pay.web.order.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import face.pay.common.order.IOrderService;
import face.pay.dao.OrderInfoDao;
import face.pay.dao.StoreInfoDao;
import face.pay.entity.OrderInfo;
import face.pay.entity.StoreInfo;
import face.pay.entity.UserInfo;
import face.pay.security.annotation.CurrentUser;
import face.pay.util.MathUtil;
import face.pay.util.page.PageData;
import face.pay.util.page.PageParam;
import face.pay.web.order.bo.OrderInfoBO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: zkj
 * @Date: 2019/8/1 11:25
 * @Description:
 */
@Controller
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderInfoDao orderInfoDao;

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private StoreInfoDao storeInfoDao;

    @RequestMapping("/list")
    public String manager() {
        return "order/list";
    }

    /**
     * 查询商户订单
     *
     * @param loginUser
     * @return
     */
    @RequestMapping("/queryData")
    @ResponseBody
    public PageData manager(@CurrentUser UserInfo loginUser, @RequestParam Map<String, Object> params, PageParam pageParam,
                            String startTime, String type, String payType, Integer storeId,Integer status) {

        return this.iOrderService.queryData(loginUser, params, pageParam, startTime, type, payType, storeId,status);
    }

    /**
     * 导出订单详细信息
     *
     * @param loginUser
     * @param startTime 查询时间
     * @param type      支付类型
     * @param payType   支付方式
     * @param storeId   门店
     * @param status  状态
     * @param response
     */
    @RequestMapping("/exportOrderInfo")
    public void exportOrderInfo(@CurrentUser UserInfo loginUser,
                                String startTime, String type, String payType,
                                Integer storeId, Integer status, HttpServletResponse response) {
        log.info("开始导出交易记录");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", loginUser.getId());
        params.put("startTime", startTime);
        params.put("type", type);
        params.put("payType", payType);
        params.put("storeId", storeId);
        params.put("status", status);

        List<OrderInfo> orderInfos = this.orderInfoDao.queryList(params);
        log.info("交易记录大小：" + orderInfos.size() + "条");
        StoreInfo storeInfo = null;
        if (storeId != null) {
            storeInfo = storeInfoDao.getById(storeId);
        }

        List<OrderInfoBO> orderInfoBOs = new ArrayList<>();
        for (OrderInfo list : orderInfos) {
            OrderInfoBO orderInfoBO = new OrderInfoBO();
            BeanUtils.copyProperties(list, orderInfoBO);
            //金额计算
            orderInfoBO.setTotalFee(MathUtil.transScaleMoney(list.getTotalFee()));
            orderInfoBO.setActFee(MathUtil.transScaleMoney(list.getActFee()));
            orderInfoBO.setActInnerFee(MathUtil.transScaleMoney(list.getActInnerFee()));
            orderInfoBO.setServiceFee(MathUtil.transScaleMoney(list.getServiceFee()));
            orderInfoBOs.add(orderInfoBO);
        }

        String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String title;  //标题
        if (storeInfo != null && StringUtils.isNotBlank(startTime)) {
            title = "门店" + storeInfo.getName() + ":" + startTime + "——" + nowDate + "交易记录";
        }else  if(storeInfo == null && StringUtils.isNotBlank(startTime)){
            title = startTime + "——" + nowDate + "交易记录";
        }else {
            title = "全部交易记录";
        }
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, ""), OrderInfoBO.class, orderInfoBOs);
        //文件名称
        String fileName = "交易记录：" + startTime + ".xls";
        log.info("表格名称：{}", fileName);
        if (workbook != null) {
            try {
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                ServletOutputStream outputStream = response.getOutputStream();
                workbook.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("导出成功，结束");
        }else{
            log.info("导出失败Workbook为空，创建工作簿失败");
        }
    }
}
